package ch.uzh.ifi.seal.ssqa.importer.code;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;

public class LinesOfCodeCounter {
	BufferedReader fileReader;
	
	/**
	 * Initializes the file that the code should be counted of
	 * @param iFile
	 */
	public LinesOfCodeCounter(IFile iFile){
		try {
			if(iFile != null && iFile.getContents() !=null)
				this.fileReader = new BufferedReader(new InputStreamReader(iFile.getContents()));
		} catch (CoreException e) {
			e.printStackTrace();
		} 
	}
	
	public LinesOfCodeCounter(InputStream inputStream){
		this.fileReader = new BufferedReader(new InputStreamReader(inputStream));
	}
	
	/**
	 * Counting all the lines that are not comments or empty lines.
	 * If the comment is going over more then one line, the skipCommend(BufferedReader reader) method is called
	 * @return int code line count
	 */
	public int getCodeLines(){
		int count = 0;
		String line;
		try {
			while((line = this.fileReader.readLine()) != null){
				line = line.trim();
				if(line.startsWith("/*") && !line.contains("*/")){
					this.skipComment(this.fileReader);
				}
				else if(!line.startsWith("//") && line != "" && !line.isEmpty()){
					count++;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return count;
	}
	
	/**
	 * Skiping all the comment lines till the end comment sign comes. 
	 */
	private void skipComment(BufferedReader reader) throws IOException{
		boolean inComment = true;
		while(inComment){
			String line = reader.readLine();
			line = line.trim();
			if(line.contains("*/")){
				inComment = false;
			}
		}
	}
	
}
